// https://leetcode.cn/problems/4sum/description/

class Solution 
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) 
    {
        vector<vector<int>> temp;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for (int i = 0; i < n - 3; i++) 
        {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < n - 2; j++) 
            {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                long long k = (long long)((long long)(target - nums[i]) - nums[j]);
                int l = j + 1, r = n - 1;
                while (l < r) 
                {
                    if (nums[l] + nums[r] < k) 
                    {
                        l++;
                    } else if (nums[l] + nums[r] > k) 
                    {
                        r--;
                    } else 
                    {
                        
                        temp.push_back({nums[i], nums[j], nums[l], nums[r]});
                        while (r - 1 > l && nums[r] == nums[r - 1]) {
                            r--;
                        }
                        while (l + 1 < r && nums[l] == nums[l + 1]) {
                            l++;
                        }
                        r--, l++;
                    }
                }
            }
        }
        return temp;
    }
};